#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <fstream>
#include <string>
#include <stdio.h>
#include <cstring>

using namespace std;

int main()
{
#if 0
    int val = 100;

    // 创建子进程
    pid_t pid = fork();
    if (pid < 0)
    {
        perror("fork error");
        exit(-1);
    }
    else if (pid == 0)
    {
        // 子进程
        cout << "I am child process" << endl;
        // sleep：让出CPU，并且不消耗CPU任何资源
        sleep(1);
        cout << "child val:" << val << endl;      
    }
    else
    {
        cout << "I am parent process" << endl;
        sleep(1);

        // 父进程
        // 程序走到这说明 pid > 0
        cout << "I am parent process" << endl;
        cout << "parent val:" << val << endl;

        int money = 999;
        cout << "parent money:" << money << endl;

        val += money;
        cout << "parent val:" << val << endl; 
    }
    cout << "hello world" << endl;
#endif

#if 1
    int money = 10000;

    // 创建子进程
    pid_t pid = fork();
    if (pid < 0)
    {
        perror("fork error");
        exit(-1);
    }
    else if (pid == 0)
    {
        sleep(3);
        // 子进程
        cout << "I am child process" << endl;
        cout << "child money:" << money << endl; 

        // 打开文件
        int fd = open("./money.txt", O_RDONLY); 
        if (fd == -1)
        {
            perror("open error");
            exit(-1);
        } 

        // 从父进程继承的资产
        int assert = 0;
        read(fd, &assert, sizeof(assert));

        close(fd);

        cout << "assert:" << assert << endl;
    }
    else
    {
        // 父进程
        // 程序走到这说明 pid > 0
        cout << "I am parent process" << endl;
        
        money += 5000000;
        cout << "parent money:" << money << endl; 
        
        // 打开文件
        int fd = open("./money.txt", O_WRONLY | O_CREAT, 0644); 
        if (fd == -1)
        {
            perror("open error");
            exit(-1);
        }

        // 向文件里写数据
        write(fd, &money, sizeof(money));

        // 关闭文件
        close(fd);
    }
    cout << "hello world" << endl;

    // 将程序卡在这的目的是为了方便开另一个终端查看进程信息
    while (1)
    {
        sleep(1);
    }

#endif

    return 0;
}